package homeWork0825;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookInFoDao {

    private static Connection conn;
    private static Statement sta;
    private static ResultSet res;
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/jdbc_demo?useUnicode=true&characterEncoding=UTF-8";
    private static String username = "root";
    private static String password = "root";

    static{
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
            sta = conn.createStatement();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //查询功能
    public static List<Map<String,Object>> excuteQuery(String sql){
        List<Map<String,Object>> books = new ArrayList<>();
        try {
            res = sta.executeQuery(sql);
            ResultSetMetaData mate = res.getMetaData();
            int count = mate.getColumnCount();
            while( res.next() ){
                Map<String,Object> book = new HashMap<>();
                for(int i = 1; i <= count;i++){
                    book.put(mate.getColumnLabel(i),res.getObject(i));
                }
                books.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return books;
    }

    //添加,删除,修改
    public static boolean excuteUpdate(String sql){
        int res = -1;
        boolean flag = false;
        try {
            res = sta.executeUpdate(sql);
            if( res > 0){
                flag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    //关闭
    public static void close(){
        if(res != null){
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                res = null;
            }
        }
        if(sta != null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                sta = null;
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                conn = null;
            }
        }
    }
}
